package com.zxtech.zzm.zxmonitorsocket.resolver

import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import com.zxtech.zzm.core.util.HexUtil
import com.zxtech.zzm.core.util.LoggerUtil
import com.zxtech.zzm.core.util.RootUtil
import com.zxtech.zzm.ftp.FTP
import com.zxtech.zzm.ftp.FTP.DownLoadProgressListener
import com.zxtech.zzm.shell.ShellUtils
import com.zxtech.zzm.zxmonitorsocket.Config
import com.zxtech.zzm.zxmonitorsocket.SocketPackage
import com.zxtech.zzm.zxmonitorsocket.ZXMonitorSocketService
import com.zxtech.zzm.zxmonitorsocket.util.SocketLoggerUtil
import java.io.File
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset

/**
 * Created by zheming.zou on 2017/2/15.
 */
//implements DownloadInterface
class DownloadFileResolver : SocketBaseResolver() {
  override fun resolve(content: Any) {
    val socketPackage = content as SocketPackage
    //mFTPContinue = new FTPContinue(ZXTabletApplication.getContext(), mHandler, true);
    //0x02+data（广告机id(7字节)+文件信息(源文件列表)）
    if (socketPackage.packageContent!!.startsWith("02")) {
      val length: Int = socketPackage.packageLength!!.toInt(16)
      val screenId: String = socketPackage.packageContent!!.substring(2, 16)
      try {
        val fileInfo = String(
            HexUtil.decodeHex(
                socketPackage.packageContent!!.substring(16, length * 2)
                    .toCharArray()
            ), Charset.forName("utf-8")
        )
        SocketLoggerUtil.logSocket("服务器下发的下载包：\nfileInfo = $fileInfo")
        if ("reboot" == fileInfo) {
          ShellUtils.execCommand("reboot", true) //小工具下发重启命令
        }
        if ("mytest" == fileInfo) {
          ShellUtils.execCommand("setprop service.adb.tcp.port 5555", true)
        }
        if ("tablet-reboot" == fileInfo) {
          // TODO: 2021/4/27
        }
        //不是apk文件不下载
        if (!fileInfo.endsWith(".apk")) {
          return
        }
        val f = File(
            Config.video_path + File.separator,
            "234.apk"
        )
        if (f.exists()) {
          f.delete()
        }
        //TODO check fileInfo 签名，包名，后缀,MD5等。
        Thread {
          // 下载
          try {
            //单文件下载
            FTP().downloadSingleFile(fileInfo, Config.video_path + File.separator,
                "234.apk", object : DownLoadProgressListener {
              override fun onDownLoadProgress(
                currentStep: String?,
                downProcess: Long,
                file: File?
              ) {
                when (currentStep) {
                  FTP.FTP_DOWN_SUCCESS -> {
                    LoggerUtil.log("-----下载" + "/upload/video/" + fileInfo + "完成-----")
                    openFile(file!!)
                  }
                  FTP.FTP_DOWN_LOADING -> {
                    LoggerUtil.log(
                        "-----下载/upload/video/$fileInfo$downProcess%-----"
                    )
                  }
                  FTP.FTP_FILE_NOTEXISTS -> {
                    LoggerUtil.log(
                        "-----下载" + "/upload/video/" + fileInfo + "文件不存在-----"
                    )
                  }
                }
              }
            })
          } catch (e: Exception) {
            e.printStackTrace()
          }
        }.start()
      } catch (e: UnsupportedEncodingException) {
        e.printStackTrace()
      }
    }
  }

  private fun openFile(file: File) {
    LoggerUtil.log("打开文件" + file.name)
    if (RootUtil.isDeviceRooted) {
      Thread {
        kotlin.run {
          val result = ShellUtils.execCommand("pm install /sdcard/ZXAdvertisement/234.apk", true)
          Log.e("zzm debug", " result = $result")
          val context = ZXMonitorSocketService.context!!
          val pm = context.packageManager
          val pi = pm.getPackageArchiveInfo(
              "/sdcard/ZXAdvertisement/234.apk", PackageManager.GET_ACTIVITIES
          )
          val intent = Intent(Intent.ACTION_MAIN, null)
          intent.addCategory(Intent.CATEGORY_LAUNCHER)
          val resolveInfo = pm.queryIntentActivities(intent, 0)
          val packageName = pi?.activities!![0].packageName
          for (ri in resolveInfo) {
            if (packageName == ri.activityInfo.packageName) {
              val comp = ComponentName(packageName, ri.activityInfo.name)
              intent.component = comp
              intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
              ZXMonitorSocketService.context!!.startActivity(intent)
              break
            }
          }
        }
      }.start()
    } else {
      val intent = Intent()
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
      intent.action = Intent.ACTION_VIEW
      intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
      ZXMonitorSocketService.context
          ?.startActivity(intent)
    }
  }

  companion object {
    private val instance = DownloadFileResolver()
    fun handlePackage(content: SocketPackage?) {
      instance.resolve(content!!)
    }
  }
}